package handler

import (
	"encoding/json"
	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes/wrappers"
	"github.com/valyala/fasthttp"
	"net/http"

	serverM "kop/modules/server/models"
	"kop/modules/sign_in/models"
)

func Login(ctx *fasthttp.RequestCtx) {

	//if string(ctx.Request.Header.ContentType()) != "application/protobuf" {
	//	ctx.SetStatusCode(http.StatusBadRequest)
	//	return
	//}

	var req wrappers.StringValue

	if err := proto.Unmarshal(ctx.PostBody(), &req); err != nil {
		ctx.Error(err.Error(), http.StatusBadRequest)
		return
	}

	login(ctx, req.Value)
}

func login(ctx *fasthttp.RequestCtx, userName string) {

	if userName == "" {
		ctx.Error("empty name", http.StatusInternalServerError)
		return
	}

	var user, err = models.GetUser(userName)
	if err != nil {
		ctx.Error(err.Error(), http.StatusInternalServerError)
		return
	}

	token, err := models.CreateToken(user.UserID)
	if err != nil {
		ctx.Error(err.Error(), http.StatusInternalServerError)
		return
	}

	var servers = serverM.GetServers()
	for _, server := range servers {
		server.TimeStamp = server.OpenTime.Unix()
	}

	var res = map[string]interface{}{"servers": servers, "token": token}
	var b, _ = json.Marshal(res)

	ctx.SetContentType("application/json")
	ctx.SetBody(b)
}

//type serversService struct {
//}
//
//func (serversService) Servers(ctx context.Context, in *empty.EmptyRequest) (*pb.ServersReply, error) {
//
//	md, ok := metadata.FromIncomingContext(ctx)
//	if !ok {
//		return nil, errors.New("令牌错误")
//	}
//
//	var tokens = md["token"]
//	if len(tokens) == 0 {
//		return nil, errors.New("令牌错误")
//	}
//
//	token := tokens[0]
//
//	_, err := models.GetUserIDFromToken(token)
//	if err != nil {
//		return nil, err
//	}
//
//	servers, err := models.FindAllServers()
//	if err != nil {
//		return nil, err
//	}
//
//	serversReply := make([]*pb.Server, 0)
//	for _, v := range servers {
//
//		serversReply = append(serversReply, &pb.Server{
//			ID:      v.ID,
//			Name:    v.Name,
//			Address: v.Address,
//		})
//	}
//
//	return &pb.ServersReply{
//		Servers: serversReply,
//	}, nil
//}
